<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { useRouter } from 'vue-router'

const router = useRouter()
const userInfo = ref({ username: '' })

const routes = ref([])
const newRoute = ref({ title: '', description: '' })
const addError = ref('')
const showEdit = ref(false)
const editRouteData = ref({ id: null, title: '', description: '' })
const editError = ref('')

// 跳转到笔记页面
function viewNotes(routeId) {
  router.push(`/route/${routeId}/notes`)
}

// 获取用户、加载数据
onMounted(() => {
  const user = localStorage.getItem('loginUser')
  if (user) userInfo.value = JSON.parse(user)
  fetchRoutes()
})

// 拉取路线
async function fetchRoutes() {
  const res = await axios.get('/api/route/list')
  if (res.data.code === 0) {
    routes.value = res.data.data
  } else {
    alert(res.data.msg)
  }
}

// 新增路线
async function addRoute() {
  addError.value = ''
  if (!newRoute.value.title) {
    addError.value = '标题不能为空'
    return
  }
  try {
    const res = await axios.post('/api/route/add', {
      ...newRoute.value,
      userId: userInfo.value.id || 1
    })
    if (res.data.code === 0) {
      fetchRoutes()
      newRoute.value.title = ''
      newRoute.value.description = ''
    } else {
      addError.value = res.data.msg
    }
  } catch (e) {
    addError.value = '网络异常'
  }
}

// 删除路线
async function deleteRoute(id) {
  if (!window.confirm('确定要删除这条路线吗？')) return
  try {
    const res = await axios.delete(`/api/route/delete/${id}`)
    if (res.data.code === 0) {
      fetchRoutes()
    } else {
      alert(res.data.msg)
    }
  } catch (e) {
    alert('删除失败，网络异常')
  }
}

// 编辑路线
function editRoute(route) {
  editRouteData.value = { ...route }
  editError.value = ''
  showEdit.value = true
}

// 保存编辑
async function saveEditRoute() {
  editError.value = ''
  if (!editRouteData.value.title) {
    editError.value = '标题不能为空'
    return
  }
  try {
    const res = await axios.put('/api/route/update', editRouteData.value)
    if (res.data.code === 0) {
      showEdit.value = false
      fetchRoutes()
    } else {
      editError.value = res.data.msg
    }
  } catch (e) {
    editError.value = '网络异常'
  }
}
</script>

<template>
  <div class="route-container">
    <!-- 顶部栏已经去掉，交给HeaderBar.vue全局组件 -->

    <el-card class="main-card">
      <template #header>
        <div style="display:flex;justify-content:space-between;align-items:center;">
          <span class="card-title">学习路线管理</span>
        </div>
      </template>

      <!-- 新增表单 -->
      <div class="add-form">
        <el-input v-model="newRoute.title" placeholder="路线标题" style="width:180px" clearable />
        <el-input v-model="newRoute.description" placeholder="路线描述" style="width:320px" clearable />
        <el-button type="primary" @click="addRoute" round>新增路线</el-button>
      </div>
      <div v-if="addError" class="err-tip">{{ addError }}</div>

      <el-table :data="routes" class="route-table" border stripe>
        <el-table-column prop="id" label="ID" width="80" align="center"/>
        <el-table-column prop="title" label="标题" align="center"/>
        <el-table-column prop="description" label="描述" align="center"/>
        <el-table-column label="操作" width="260" align="center">
          <template #default="scope">
            <el-button size="small" @click="editRoute(scope.row)" round>编辑</el-button>
            <el-button size="small" type="danger" @click="deleteRoute(scope.row.id)" round>删除</el-button>
            <el-button size="small" type="success" @click="viewNotes(scope.row.id)" round>查看笔记</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 编辑弹窗 -->
    <el-dialog v-model="showEdit" title="编辑路线" width="400px" center>
      <el-input v-model="editRouteData.title" placeholder="路线标题" style="margin-bottom:18px" clearable />
      <el-input v-model="editRouteData.description" placeholder="路线描述" clearable />
      <div v-if="editError" class="err-tip" style="margin:10px 0;">{{ editError }}</div>
      <template #footer>
        <el-button @click="showEdit = false">取消</el-button>
        <el-button type="primary" @click="saveEditRoute">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.route-container {
  min-height: 100vh;
  background: #f7f8fa;
  padding: 0 0 60px 0;
}
.main-card {
  max-width: 1020px;
  margin: 0 auto;
  border-radius: 18px;
  box-shadow: 0 4px 32px rgba(70,110,150,0.08);
}
.card-title {
  font-size: 19px;
  font-weight: bold;
  color: #16529e;
}
.add-form {
  display: flex;
  gap: 16px;
  margin-bottom: 18px;
  margin-top: 10px;
  align-items: center;
}
.err-tip {
  color: #e56c6c;
  margin-bottom: 12px;
}
.route-table {
  border-radius: 14px;
  overflow: hidden;
  font-size: 15px;
  margin-top: 18px;
}
</style>